<template>
  <el-dialog
    :visible.sync="visible"
    :title="dataForm.strategyId ? '编辑策略' : '添加策略'"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="dataForm"
      label-position="right"
      label-width="100px"
      style="margin-left: 15px"
    >
      <el-form-item label="策略名称" prop="strategyName">
        <el-input
          v-model="dataForm.strategyName"
          placeholder="请输入策略名称"
          style="width: 400px"
        />
      </el-form-item>
      <!-- <el-input v-model="dataForm.investName" placeholder="请选择投顾" readonly style="width: 400px;">
        <el-button slot="append" icon="el-icon-search" @click="selectHandle"></el-button>
      </el-input> -->
      <el-form-item label="所属投顾" prop="investName">
        <el-select
          v-model="dataForm.investName"
          filterable
          remote
          placeholder="请输入搜索关键字"
          :remote-method="querySearchAsync"
          :loading="querySearchAsync_loading"
          style="width: 400px"
        >
          <div class="policyManage_add_select">
            <span class="name tof">投顾名称</span>
            <span class="contacts tof">联系人</span>
          </div>
          <el-option
            v-for="item in querySearchAsync_list"
            :key="item.investId"
            :label="item.investName"
            :value="item.investId + '^^^' + item.investName"
          >
            <span class="policyManage_add_select_tleft tof">
              {{ item.investName }}
            </span>
            <span class="policyManage_add_select_tright tof">
              {{ item.investContacts }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="投资风格" prop="styleList">
        <el-radio
          v-model="dataForm.styleList"
          :label="item.styleId"
          v-for="item in dict.style"
          :key="item.styleId"
        >
          {{ item.styleName }}
        </el-radio>
      </el-form-item>
      <el-form-item label="投资市场" prop="marketList">
        <el-checkbox-group v-model="dataForm.marketList" style="width: 600px">
          <el-checkbox
            v-for="item in dict.market"
            :label="item.id"
            :key="item.id"
          >
            {{ item.strategyMarket }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-show="dataForm.marketList.length"
        label="投资方法"
        prop="methodList"
      >
        <el-checkbox-group v-model="dataForm.methodList" style="width: 600px">
          <el-checkbox
            v-for="item in computeMethod"
            :label="item.methodId"
            :key="item.methodId"
          >
            {{ item.strategyMethod }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-show="dataForm.marketList.length"
        label="投资标的"
        prop="subjectList"
      >
        <el-checkbox-group v-model="dataForm.subjectList" style="width: 600px">
          <el-checkbox
            v-for="item in computeSubject"
            :label="item.id"
            :key="item.id"
          >
            {{ item.strategySubject }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="对标指数" prop="investIndex">
        <indexSelectTree
          v-if="visible"
          :width="400"
          :maxNum="5"
          :indexType.sync="dataForm.investIndex"
          @contrastOptionsObj="contrastOptionsObjHandle"
        ></indexSelectTree>
      </el-form-item>
      <el-form-item label="净值类型" prop="strategyNetWorthStyle">
        <el-radio v-model="dataForm.strategyNetWorthStyle" :label="0">
          单利
        </el-radio>
        <span style="font-size: 11px; color: #999; line-height: 22px">
          (当日净值-前一日净值)/基准日净值
        </span>
        <br />
        <el-radio v-model="dataForm.strategyNetWorthStyle" :label="1">
          复利
        </el-radio>
        <span style="font-size: 11px; color: #999; line-height: 22px">
          (当日净值-前一日净值)/前一日净值
        </span>
      </el-form-item>
      <el-form-item class="tag-formItem" label="自定义标签" prop="tagList">
        <el-input
          v-model="tagListText"
          type="textarea"
          :rows="3"
          :placeholder="tagList_placeholder"
          style="width: 600px"
        ></el-input>
      </el-form-item>
      <div class="tagBox">
        <span
          class="tag"
          v-for="(item, i) in dict2.tagList"
          :key="i"
          @click="tagListTextHandle(item)"
        >
          {{ item }}
        </span>
      </div>
      <el-form-item label="采集方式">
        <el-select v-model="dataForm.addType" placeholder="请选择">
          <el-option
            v-for="item in addTypeOpt"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        style="display: inline-block"
        label="采集器编号"
        v-if="dataForm.addType === 1"
      >
        <el-select v-model="dataForm.dataId" placeholder="请选择">
          <el-option
            v-for="item in collectOpt"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        style="display: inline-block"
        label="IP地址："
        prop="ipAddr"
        v-if="dataForm.addType === 1"
      >
        <el-input
          v-model="dataForm.ipAddr"
          placeholder="000.000.000.000 ~ 255.255.255.255"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="采集目录/文件" v-if="dataForm.addType === 1">
        <el-input
          v-model="dataForm.filePath"
          placeholder="请输入"
          style="width: 300px"
        ></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="addSubmit()">提交</el-button>
    </div>

    <investManageOpen
      v-if="selectVisible"
      ref="investManageOpen"
      @selctInvestManage="selctInvestManage"
    ></investManageOpen>
  </el-dialog>
</template>

<script>
import investManageOpen from "@/views/afterManage/afterInvest/investManageOpen.vue";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import {
  addOrUpdateStrategyInfo,
  findStrategyExtraInfoById,
} from "@/api/policyManage";
import { fetchList } from "@/api/investManage";

export default {
  components: { investManageOpen, indexSelectTree },
  data() {
    const valiIpAddr = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (
        !/^((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))$/.test(
          value
        )
      ) {
        callback(new Error("请输入正确ip地址格式"));
      }
      callback();
    };
    return {
      visible: false,
      selectVisible: false,
      dict: [],
      dict2: [],
      addTypeOpt: [
        { value: 0, label: "手工录入" },
        { value: 1, label: "自动采集" },
        { value: 2, label: "接口上报" },
      ],
      collectOpt: [
        { value: 0, label: "01" },
        { value: 1, label: "02" },
        { value: 2, label: "03" },
        { value: 3, label: "04" },
        { value: 4, label: "05" },
        { value: 5, label: "06" },
        { value: 6, label: "07" },
        { value: 7, label: "08" },
        { value: 8, label: "09" },
        { value: 9, label: "10" },
      ],
      contrastOptionsObj: {},
      dataForm: {
        strategyId: "",
        strategyName: "",
        investName: "",
        dataId: 0, // 采集器编号
        filePath: "", // 采集目录
        addType: 0, // 采集方式
        ipAddr: "", // 采集ip
        makeTime: undefined,
        investIndex: "",
        strategyBenchmarkingIndex: "",
        styleList: "",
        marketList: [],
        methodList: [],
        subjectList: [],
        strategyNetWorthStyle: 0,
      },
      tagListText: "",
      tagListText_list: [],
      tagList_placeholder:
        "自定义标签名称，多个标签用空格、逗号隔开， \n如：股票，期权，期货",
      querySearchAsync_loading: false,
      querySearchAsync_list: [],
      rules: {
        ipAddr: [{ validator: valiIpAddr, trigger: "blur" }],
        strategyName: [
          { required: true, message: "策略名称必填", trigger: "blur" },
        ],
        investName: [
          { required: true, message: "所属投顾必填", trigger: "change" },
        ],
        makeTime: [
          { required: true, message: "成立时间必填", trigger: "change" },
        ],
        styleList: [
          { required: true, message: "投资风格必填", trigger: "change" },
        ],
        marketList: [
          { required: true, message: "投资市场必填", trigger: "change" },
        ],
        methodList: [
          { required: true, message: "投资方法必填", trigger: "change" },
        ],
        subjectList: [
          { required: true, message: "投资标的必填", trigger: "change" },
        ],
      },
    };
  },
  props: {
    strategyPool: {
      type: Number,
    },
  },
  computed: {
    computeMethod() {
      let res = [];
      this.dataForm.marketList.forEach((id) => {
        const list = this.dict2.market.find((item) => item.id == id).method;
        res = [...new Set([...res, ...list])].filter(
          (item) => !res.includes(item) || !list.includes(item)
        );
      });
      return res;
    },
    computeSubject() {
      let res = [];
      this.dataForm.marketList.forEach((id) => {
        const list = this.dict2.market.find((item) => item.id == id).subject;
        res = [...new Set([...res, ...list])].filter(
          (item) => !res.includes(item) || !list.includes(item)
        );
      });
      return res;
    },
  },
  watch: {
    "dataForm.investIndex": {
      handler(newList, oldList) {
        if (newList.length > 5) {
          this.$message({
            message: "最多选择5个对比指标",
            type: "warning",
            duration: 2000,
          });
          this.$nextTick(() => {
            this.dataForm.investIndex = oldList;
          });
        }
      },
    },
  },
  methods: {
    init(strategyId, dict, dict2, userId, investId, investName) {
      this.visible = true;
      this.dict = dict;
      this.dict2 = dict2;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        (this.dataForm = {
          strategyId: "",
          strategyName: "",
          investId: "",
          investName: "",
          makeTime: undefined,
          investIndex: "",
          strategyBenchmarkingIndex: "",
          styleList: "",
          dataId: 0,
          filePath: "",
          addType: 0,
          ipAddr: "",
          marketList: [],
          methodList: [],
          subjectList: [],
          strategyNetWorthStyle: 0,
        }),
          (this.tagListText = "");
        this.dataForm.createdBy = userId;
        if (investId) this.dataForm.investId = investId;
        if (investName) this.dataForm.investName = investName;
        if (strategyId) this.findStrategyExtraInfoById(strategyId, userId);
      });
    },
    querySearchAsync(investName) {
      if (investName) {
        this.querySearchAsync_loading = true;
        fetchList({
          userId: this.dataForm.createdBy,
          strategyPool: this.strategyPool,
          adviserName: investName,
          pageCurrent: 1,
          limit: 10000000,
        }).then((res) => {
          this.querySearchAsync_loading = false;
          console.log("投顾管理", res);
          this.querySearchAsync_list = res.body.list;
        });
      } else {
        this.querySearchAsync_list = [];
      }
    },
    findStrategyExtraInfoById(strategyId, userId) {
      findStrategyExtraInfoById({
        strategyId,
        userId: Number(userId),
      }).then((res) => {
        const row = res.body[0];
        this.dataForm.strategyId = row.strategyInfoVo.strategyId;
        this.dataForm.strategyName = row.strategyInfoVo.strategyName;
        this.dataForm.investId = row.strategyInfoVo.investId;
        this.dataForm.investName = row.strategyInfoVo.investName;
        this.dataForm.makeTime = row.strategyInfoVo.makeTime;
        this.dataForm.investIndex = row.strategyInfoVo.investIndex;
        this.dataForm.styleList = row.strategyInfoVo.styleIdList;
        this.dataForm.marketList = row.strategyInfoVo.marketIdList;
        this.dataForm.methodList = row.strategyInfoVo.methodIdList;
        this.dataForm.subjectList = row.strategyInfoVo.subjectIdList;
        this.dataForm.ipAddr = row.strategyInfoVo.ipAddr;
        this.dataForm.dataId = row.strategyInfoVo.dataId;
        this.dataForm.filePath = row.strategyInfoVo.filePath;
        this.dataForm.addType = row.strategyInfoVo.addType;
        this.dataForm.strategyNetWorthStyle =
          row.strategyInfoVo.strategyNetWorthStyle;
        this.tagListText = row.strategyInfoVo.tagList.join(",");
      });
    },
    contrastOptionsObjHandle(obj) {
      this.contrastOptionsObj = obj;
    },
    selectHandle() {
      this.selectVisible = true;
      this.$nextTick(() => {
        this.$refs.investManageOpen.init();
      });
    },
    selctInvestManage(investName) {
      this.dataForm.investName = investName;
    },
    tagListTextHandle(t) {
      const list = this.tagListText.split(/[,， \n]+/);
      if (list.indexOf(t) == -1) {
        if (list.length == 1 && list[0] === "") {
          this.tagListText = t;
        } else {
          this.tagListText = this.tagListText + "，" + t;
        }
      }
    },
    addSubmit() {
      if (this.dataForm.investName.indexOf("^^^") == -1) {
        if (this.dataForm.investId) {
          this.dataForm.investName =
            this.dataForm.investId + "^^^" + this.dataForm.investName;
        } else {
          this.$message({
            type: "error",
            message: "投顾数据出了问题，请重新选择投顾尝试",
          });
          return;
        }
      }
      this.dataForm.tagList = this.tagListText.split(/[,， \n]+/);

      if (this.dataForm.investIndex.length) {
        const index_list = this.dataForm.investIndex.map(
          (item) => this.contrastOptionsObj[item]
        );
        this.dataForm.strategyBenchmarkingIndex = index_list.join(",");
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addOrUpdateStrategyInfo({
            strategyPool: this.strategyPool,
            ...this.dataForm,
          }).then((res) => {
            this.$notify({
              type: "success",
              message: res.msg,
              duration: 2000,
            });
            this.visible = false;
            this.$emit("closeOpen");
          });
        }
      });
    },
    // ip正则
    dataIdCheck() {
      const reg =
        /^((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))$/.test(
          this.dataId
        );
      console.log(reg);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 600px;
  overflow-y: auto;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;

  // 全局默认滚动条
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
    border-radius: 2px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
    background: rgba(0, 0, 0, 0.1);
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
    border-radius: 10px;
    background: #ededed;
  }
}
.tag-formItem {
  margin-bottom: 0px !important;
}
.tagBox {
  width: 600px;
  margin-left: 100px;
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  .tag {
    line-height: 1;
    padding: 4px 8px;
    border-radius: 2px;
    margin: 8px 8px 0 0;
    cursor: pointer;
    user-select: none;
    border: 1px solid #d9d9d9;
  }
}
</style>

<style lang="scss">
.policyManage_add_autocomplete {
  .el-autocomplete-suggestion__wrap {
    padding-top: 0;
  }
  ul li {
    padding: 0 12px;
  }
  ul li:hover .title {
    background: #fff;
  }
  ul li .title {
    width: 400px;
    line-height: 34px;
    margin-left: -12px;
    padding: 0 12px;
    display: flex;
    border: 1px solid #f0f0f0;
    font-size: 12px;
    color: #666666;
    user-select: none;
    pointer-events: none;
    &:hover {
      background: #fff;
    }
    .name {
      width: 280px;
    }
    .contacts {
      width: 100px;
    }
  }
  ul li .paa-content {
    display: flex;
    .name {
      width: 280px;
    }
    .contacts {
      width: 100px;
    }
  }
}

.policyManage_add_select {
  line-height: 34px;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 12px;
  color: #666666;
  border-bottom: 1px solid #f0f0f0;
  .name {
    width: 300px;
  }
  .contacts {
    width: 90px;
  }
}
.policyManage_add_select_tleft {
  float: left;
  width: 300px;
}
.policyManage_add_select_tright {
  float: right;
  width: 90px;
}
</style>
